<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import ChatMessage from '../components/ChatMessage.vue'
// 导入Element Plus图标 - 只保留使用到的图标
import {ChatDotRound, Key, More, Plus, Position, Refresh, SwitchButton, Edit, Close, Setting, User, Document} from '@element-plus/icons-vue'
import {getStoredUser, logout, resetPassword} from '../api/auth'
import type {Chat} from '../api/chat'
import {createChat, deleteChat, getChatList, getChatMessages, getProviderList, getRoleList, type ChatAgentRole, type ProviderInfo} from '../api/chat'
// 使用统一的markdown工具
import { parseMarkdown } from '../utils/markdown'
import {Cache} from '../utils/cache'

interface Message {
  id: string
  role: 'system' | 'user' | 'assistant'
  content: string
  timestamp: number
  // 思考相关字段
  reasoning?: string  // 思考内容
  isThinking?: boolean  // 是否正在思考
  thinkingComplete?: boolean  // 思考是否完成
}



// 状态变量
const inputMessage = ref('')
const messages = ref<Message[]>([])
const loading = ref(false)
const chatContainerRef = ref<HTMLElement | null>(null)
const sidebarExpanded = ref(true)
const chatList = ref<Chat[]>([])
const currentChatId = ref<number | null>(null)
const loadingChatList = ref(false)
// 缓存刷新控制变量
const cacheRefreshVisible = ref(false)
const refreshing = ref(false)

// 对话弹框控制
const chatDialogVisible = ref(false)
const currentDialogMessage = ref<Message | null>(null)
const dialogTitle = ref('')

// 弹窗控制
const createChatDialogVisible = ref(false)
const renameChatDialogVisible = ref(false)
const renameValue = ref('')
const currentRenameChatId = ref<number | null>(null)

// 新对话表单
const newChatForm = ref({
  name: '', // 对话名称，非必填
  useSystemPrompt: 0, // 默认不启用系统指令
  systemPrompt: '',
  roleId: null as number | null,
  systemContext: ''
})

// 新增角色相关的响应式数据
const roleList = ref<ChatAgentRole[]>([])
const selectedRoleId = ref<number | null>(null)
const showCustomPrompt = ref(false)

// 计算属性：获取选中的角色对象
const selectedRole = computed(() => {
  return roleList.value.find(role => role.id === selectedRoleId.value)
})

// 判断是否为自定义角色
const isCustomRole = computed(() => {
  return selectedRole.value?.type === 4
})

// 高级设置折叠面板控制
const showAdvancedSettings = ref(false)
const createChatLoading = ref(false)





// 从localStorage获取用户信息
const currentUser = computed(() => {
  return getStoredUser() || {username: '用户', nickname: '用户', avatar: ''}
})

// 按时间段分类聊天
const todayChats = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  return chatList.value.filter(chat => {
    const chatDate = new Date(chat.CreatedAt)
    return chatDate >= today
  })
})

const weekChats = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  const weekStart = new Date(today)
  weekStart.setDate(today.getDate() - today.getDay()) // 设置为本周第一天

  const todayEnd = new Date()
  todayEnd.setHours(23, 59, 59, 999)

  return chatList.value.filter(chat => {
    const chatDate = new Date(chat.CreatedAt)
    return chatDate >= weekStart && chatDate < today
  })
})

const monthChats = computed(() => {
  const today = new Date()
  today.setHours(0, 0, 0, 0)

  const monthStart = new Date(today.getFullYear(), today.getMonth(), 1)
  const weekStart = new Date(today)
  weekStart.setDate(today.getDate() - today.getDay()) // 设置为本周第一天

  return chatList.value.filter(chat => {
    const chatDate = new Date(chat.CreatedAt)
    return chatDate >= monthStart && chatDate < weekStart
  })
})

const olderChats = computed(() => {
  const monthStart = new Date()
  monthStart.setHours(0, 0, 0, 0)
  monthStart.setDate(1) // 本月第一天

  return chatList.value.filter(chat => {
    const chatDate = new Date(chat.CreatedAt)
    return chatDate < monthStart
  })
})

// 重置创建表单
const resetCreateForm = () => {
  newChatForm.value = {
    name: '',
    useSystemPrompt: 0,
    systemPrompt: '',
    roleId: roleList.value.length > 0 ? roleList.value[0].id : null,
    systemContext: ''
  }
  selectedRoleId.value = roleList.value.length > 0 ? roleList.value[0].id : null
  showCustomPrompt.value = false
  showAdvancedSettings.value = false
}

// 显示创建对话弹窗
const showCreateChatDialog = () => {
  // 重置表单状态
  resetCreateForm()
  createChatDialogVisible.value = true
}



// 处理对话操作
const handleHistoryAction = (command: string, chatId: number) => {
  if (command === 'delete') {
    handleDeleteChat(chatId)
  } else if (command === 'rename') {
    // 获取当前对话名称
    const chat = chatList.value.find(c => c.ID === chatId)
    if (chat) {
      renameValue.value = chat.name
      currentRenameChatId.value = chatId
      renameChatDialogVisible.value = true
    }
  }
}

// 确认重命名
const handleRenameConfirm = async () => {
  if (!currentRenameChatId.value || !renameValue.value.trim()) {
    return
  }

  try {
    // 这里需要添加重命名API，暂时只更新本地状态
    // TODO: 添加重命名API
    const index = chatList.value.findIndex(chat => chat.ID === currentRenameChatId.value)
    if (index !== -1) {
      chatList.value[index].name = renameValue.value
      ElMessage.success('重命名成功')
      renameChatDialogVisible.value = false
    }
  } catch (error) {
    console.error('重命名失败:', error)
    ElMessage.error('重命名失败')
  }
}

// 重置密码弹框控制
const resetPasswordDialogVisible = ref(false)
const resetPasswordForm = ref({
  username: '',
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})
const resetPasswordLoading = ref(false)

// 生成随机ID
const generateId = (): string => {
  return Date.now() + Math.random().toString(36).substring(2, 9)
}

// 滚动到最新消息
const scrollToBottom = async (): Promise<void> => {
  await nextTick()
  if (chatContainerRef.value) {
    const messagesContainer = chatContainerRef.value.querySelector('.messages-container')
    if (messagesContainer) {
      messagesContainer.scrollTop = messagesContainer.scrollHeight
    }
  }
}

// 复制消息内容
const copyMessageContent = () => {
  if (currentDialogMessage.value && typeof navigator !== 'undefined' && navigator.clipboard) {
    navigator.clipboard.writeText(currentDialogMessage.value.content)
        .then(() => {
          ElMessage.success('复制成功')
        })
        .catch((err) => {
          console.error('复制失败:', err)
          ElMessage.error('复制失败')
        })
  }
}

// 发送消息
const sendMessage = async (): Promise<void> => {
  // 验证消息内容，避免发送空消息或正在加载时发送
  if (!inputMessage.value.trim() || loading.value) return

  // 如果当前没有聊天会话，先创建一个
  if (!currentChatId.value) {
    await createNewChat()
    // 如果创建失败，直接返回
    if (!currentChatId.value) {
      return
    }
  }

  // 添加用户消息
  const userMessage: Message = {
    id: generateId(),
    role: 'user',
    content: inputMessage.value,
    timestamp: Date.now()
  }

  // 将用户消息添加到消息列表
  messages.value.push(userMessage)

  inputMessage.value = '' // 清空输入框

  // 滚动到最新消息
  await scrollToBottom()

  // 显示加载状态
  loading.value = true

  try {
    // 构建SSE URL - 使用相对路径
    // 当应用部署在Go后端时，请求会自动发送到当前主机和端口
    // 而不是使用固定的环境变量URL

    const baseUrl = import.meta.env.VITE_API_BASE_URL || window.location.origin;
    const req = baseUrl.replace(/\/$/, '') + '/chat/question/sse';
    const sseUrl = new URL(req);
    sseUrl.searchParams.set('id', currentChatId.value.toString());
    sseUrl.searchParams.set('message', userMessage.content);
    
    // 使用供应商的实际ID
    const selectedProviderInfo = providers.value.find(p => p.name === selectedProvider.value);
    const agentId = selectedProviderInfo ? selectedProviderInfo.id.toString() : '1';
    
    // 动态获取默认模型
    const defaultModel = selectedModel.value || 
      (selectedProviderInfo && selectedProviderInfo.models.length > 0 ? selectedProviderInfo.models[0] : '');
    
    sseUrl.searchParams.set('model', defaultModel);
    sseUrl.searchParams.set('agent', agentId);

    // 创建 EventSource 实例
    const eventSource = new EventSource(sseUrl.toString())

    // 全局流式消息状态
    let currentStreamingMessage: Message | null = null;
    
    // 初始化流式消息（只在第一次调用时创建）
    const initStreamingMessage = (): Message => {
      if (currentStreamingMessage) {
        return currentStreamingMessage;
      }
      
      // 检查是否已有未完成的assistant消息
      const existingMessage = messages.value.find(msg => 
        msg.role === 'assistant' && 
        (msg.isThinking === true || msg.thinkingComplete === false)
      );
      
      if (existingMessage) {
        currentStreamingMessage = existingMessage;
        currentStreamingMessageId.value = existingMessage.id;
        return existingMessage;
      }
      
      // 创建新消息
      const newMessage: Message = {
        id: generateId(),
        role: 'assistant' as const,
        content: '',
        timestamp: Date.now(),
        reasoning: '',
        isThinking: false,
        thinkingComplete: false
      };
      
      currentStreamingMessage = newMessage;
      currentStreamingMessageId.value = newMessage.id;
      messages.value.push(newMessage);
      
      console.log('创建新流式消息:', newMessage.id);
      return newMessage;
    };
    
    // 更新流式消息
    const updateCurrentMessage = (updates: Partial<Message>) => {
      if (!currentStreamingMessage) return;
      
      const messageIndex = messages.value.findIndex(msg => msg.id === currentStreamingMessage!.id);
      if (messageIndex === -1) return;
      
      // 直接修改消息对象的属性
      Object.assign(messages.value[messageIndex], updates);
      Object.assign(currentStreamingMessage, updates);
      
      console.log('更新消息:', updates);
    };
    
    // 重置流式状态
    const resetStreamingState = () => {
      currentStreamingMessage = null;
      streamingContent.value = '';
      streamingReasoning.value = '';
      currentStreamingMessageId.value = null;
      hasReasoningContent.value = false;
      streamingComplete.value = true;
      console.log('重置流式状态');
    };

    // 处理SSE事件
    eventSource.addEventListener('connected', (event: MessageEvent) => {
      console.log('SSE连接已建立:', event.data);
      // 重置状态
      resetStreamingState();
    })

    eventSource.addEventListener('start', (event: MessageEvent) => {
      console.log('开始生成回复:', event.data);
      // 重置状态，准备新的流式消息
      resetStreamingState();
      // 预先创建消息对象
      initStreamingMessage();
    });

    eventSource.addEventListener('reason', (event: MessageEvent) => {
      const reasonChunk = event.data;
      console.log('收到reason:', reasonChunk);
      
      hasReasoningContent.value = true;
      streamingReasoning.value += reasonChunk;
      
      // 确保消息存在
      
      // 更新reasoning
      updateCurrentMessage({
        reasoning: streamingReasoning.value,
        isThinking: true
      });
      
      nextTick(() => {
        scrollToBottom();
      });
    });

    eventSource.addEventListener('chunk', (event: MessageEvent) => {
      const chunk = event.data;
      console.log('收到chunk:', chunk);
      
      streamingContent.value += chunk;
      
      // 确保消息存在
      
      // 更新content
      updateCurrentMessage({
        content: streamingContent.value,
        isThinking: false
      });
      
      nextTick(() => {
        scrollToBottom();
      });
    });

    eventSource.addEventListener('done', (event: MessageEvent) => {
      try {
        const data = JSON.parse(event.data);
        
        if (currentStreamingMessage) {
          // 最终更新
          updateCurrentMessage({
            content: data.fullResponse || streamingContent.value,
            reasoning: data.fullReason || streamingReasoning.value,
            isThinking: false,
            thinkingComplete: true
          });
          
          console.log('完成消息更新');
        }
        
        // 标记流式完成
        streamingComplete.value = true;
        
      } catch (error) {
        console.error('解析done消息失败:', error);
      } finally {
        eventSource.close();
        loading.value = false;
        resetStreamingState();
        scrollToBottom();
      }
    });

    eventSource.addEventListener('error', () => {
      console.log('SSE连接错误');
      eventSource.close();
      loading.value = false;

      if (!currentStreamingMessage) {
        // 只有在没有流式消息时才创建错误消息
        const errorMessage: Message = {
          id: generateId(),
          role: 'assistant' as const,
          content: '抱歉，我遇到了问题，无法回答您的问题。请稍后再试。',
          timestamp: Date.now()
        };
        messages.value.push(errorMessage);
      } else {
        // 标记现有消息为完成状态
        updateCurrentMessage({
          isThinking: false,
          thinkingComplete: true
        });
      }
      
      resetStreamingState();
      scrollToBottom();
    })
  } catch (error) {
    console.error('发送消息出错:', error)
    ElMessage.error('抱歉，发生了错误，请稍后再试。')
    loading.value = false

    // 添加错误消息
    messages.value.push({
      id: generateId(),
      role: 'assistant' as const,
      content: '抱歉，我遇到了问题，无法回答您的问题。请稍后再试。',
      timestamp: Date.now()
    })
    scrollToBottom()
  }
}

// 预加载
const preloadComponents = () => {
  // 空闲时预加载其他组件
  window.requestIdleCallback = window.requestIdleCallback || ((cb) => setTimeout(cb, 1))
  window.requestIdleCallback(() => {
    // 预加载可能需要的组件
    console.debug('预加载聊天相关组件')
  })
}

// 当屏幕可见性变化时预加载
if (typeof document !== 'undefined') {
  document.addEventListener('visibilitychange', () => {
    if (document.visibilityState === 'visible') {
      preloadComponents()
    }
  })
}

// 生命周期钩子
onMounted(async () => {
  // 初始化界面时，加载聊天列表和初始化提供商和模型列表
  await Promise.all([
    fetchChatList(),
    fetchRoleList(),
    fetchProviders() // 新增：获取供应商列表
  ])

  // 检查URL中是否有chatId参数
  const urlParams = new URLSearchParams(window.location.search);
  const chatIdParam = urlParams.get('id');

  if (chatIdParam && Number(chatIdParam)) {
    // 如果URL中有chatId参数，加载该聊天
    currentChatId.value = Number(chatIdParam);
    await loadChatMessages(Number(chatIdParam));
  } else {
    // 显示欢迎页面，设置默认问候语
    currentChatId.value = null;
    messages.value = [
      {
        id: generateId(),
        role: 'assistant',
        content: '欢迎使用布丁AI助手，我可以帮您回答问题、编写代码、创作内容等。请告诉我您需要什么帮助？',
        timestamp: Date.now()
      }
    ];
  }

  // 预加载组件
  preloadComponents()

  // 为整个页面添加键盘事件，确保在任何地方按Esc都能关闭对话框
  document.addEventListener('keydown', (e) => {
    if (e.key === 'Escape') {
      createChatDialogVisible.value = false
      renameChatDialogVisible.value = false
      resetPasswordDialogVisible.value = false
      chatDialogVisible.value = false
    }
  })
})

// 组件卸载时清理事件监听器，避免内存泄露
onBeforeUnmount(() => {
  if (typeof document !== 'undefined') {
    document.removeEventListener('visibilitychange', () => {
    })
    document.removeEventListener('keydown', () => {
    })
  }
})

// 处理重置密码弹窗显示
const showResetPasswordDialog = () => {
  resetPasswordForm.value = {
    username: currentUser.value.username,
    oldPassword: '',
    newPassword: '',
    confirmPassword: ''
  }
  resetPasswordDialogVisible.value = true
}

// 处理退出登录
const handleLogout = async () => {
  try {
    await ElMessageBox.confirm('确定要退出登录吗？', '退出确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    // 执行登出操作
    logout()
    // 重定向到主页
    window.location.href = '/'
  } catch (error) {
    // 用户取消登出或出现错误
    console.log('登出操作已取消')
  }
}

// 提交重置密码
const submitResetPassword = async () => {
  // 验证表单
  if (!resetPasswordForm.value.oldPassword) {
    ElMessage.warning('请输入当前密码')
    return
  }

  if (!resetPasswordForm.value.newPassword) {
    ElMessage.warning('请输入新密码')
    return
  }

  if (resetPasswordForm.value.newPassword !== resetPasswordForm.value.confirmPassword) {
    ElMessage.warning('两次输入的新密码不一致')
    return
  }

  // 密码长度验证
  if (resetPasswordForm.value.newPassword.length < 6) {
    ElMessage.warning('新密码长度不能少于6个字符')
    return
  }

  resetPasswordLoading.value = true

  try {
    const response = await resetPassword(
        resetPasswordForm.value.username,
        resetPasswordForm.value.oldPassword,
        resetPasswordForm.value.newPassword
    )

    if (response.code === 200) {
      ElMessage.success('密码重置成功，请重新登录')
      resetPasswordDialogVisible.value = false

      // 密码修改成功后自动登出
      setTimeout(() => {
        logout()
        window.location.href = '/login'
      }, 1500)
    } else {
      ElMessage.error(response.msg || '密码重置失败')
    }
  } catch (error) {
    console.error('重置密码出错:', error)
    ElMessage.error('密码重置失败，请稍后再试')
  } finally {
    resetPasswordLoading.value = false
  }
}

// 加载聊天历史记录
const loadChatHistory = async (chatId: number): Promise<void> => {
  await switchChat(chatId)
}

// 获取角色列表
const fetchRoleList = async () => {
  try {
    const response = await getRoleList()
    if (response.code === 200 && response.data) {
      roleList.value = response.data
      // 默认选择第一个角色（如果有的话）
      if (roleList.value.length > 0) {
        selectedRoleId.value = roleList.value[0].id
        newChatForm.value.roleId = roleList.value[0].id
      }
    } else {
      ElMessage.error(response.msg || '获取角色列表失败')
    }
  } catch (error) {
    console.error('获取角色列表失败:', error)
    ElMessage.error('获取角色列表失败')
  }
}















// 切换对话
const switchChat = async (chatId: number): Promise<void> => {
  if (chatId === currentChatId.value) return

  currentChatId.value = chatId || null
  messages.value = [] // 清空消息列表

  // 加载对话消息
  await loadChatMessages(chatId)
}

// 根据对话ID加载消息列表
const loadChatMessages = async (chatId: number): Promise<void> => {
  loading.value = true
  const originalMessages = [...messages.value] // 备份当前消息

  try {
    const response = await getChatMessages(chatId)

    // 清空当前消息列表
    messages.value = []

    if (response.code === 200) {
      // 如果有消息数据
      if (response.data && response.data.length > 0) {
        // 将API返回的消息转换为本地格式
        response.data.forEach(msg => {
          messages.value.push({
            id: generateId(),
            role: msg.role as 'system' | 'user' | 'assistant',
            content: msg.content,
            timestamp: new Date(msg.timestamp).getTime()
          })
        })
      } else {
        // 如果没有消息数据，添加默认欢迎消息
        messages.value = [{
          id: generateId(),
          role: 'assistant',
          content: '欢迎使用布丁AI助手，我可以帮您回答问题、编写代码、创作内容等。请告诉我您需要什么帮助？',
          timestamp: Date.now()
        }]
      }

      // 滚动到最新消息
      await scrollToBottom()
    } else {
      // 请求失败时恢复原消息或显示默认消息
      messages.value = originalMessages.length > 0 ? originalMessages : [{
        id: generateId(),
        role: 'assistant',
        content: '欢迎使用布丁AI助手，我可以帮您回答问题、编写代码、创作内容等。请告诉我您需要什么帮助？',
        timestamp: Date.now()
      }]
      ElMessage.error(response.msg || '获取聊天消息失败')
    }
  } catch (error) {
    console.error('获取聊天消息出错:', error)
    // 错误时恢复原消息或显示默认消息
    messages.value = originalMessages.length > 0 ? originalMessages : [{
      id: generateId(),
      role: 'assistant',
      content: '欢迎使用布丁AI助手，我可以帮您回答问题、编写代码、创作内容等。请告诉我您需要什么帮助？',
      timestamp: Date.now()
    }]
    ElMessage.error('获取聊天消息失败')
  } finally {
    loading.value = false
  }
}

// 删除聊天会话
const handleDeleteChat = async (chatId: number): Promise<void> => {
  try {
    await ElMessageBox.confirm('确定要删除这个对话吗？此操作不可恢复。', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteChat(chatId)

    if (response.code === 200) {
      ElMessage.success('删除成功')

      // 如果删除的是当前对话，则清空当前对话ID和消息
      if (currentChatId.value === chatId) {
        currentChatId.value = null
        messages.value = []
      }

      // 刷新聊天列表
      await fetchChatList()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除聊天出错:', error)
      ElMessage.error('删除失败')
    }
  }
}

// 模型选择相关
const selectedModel = ref('')

// AI提供商选择相关
const providers = ref<ProviderInfo[]>([])
const selectedProvider = ref('')
const loadingProviders = ref(false)

// 获取聊天列表
const fetchChatList = async (): Promise<void> => {
  loadingChatList.value = true
  try {
    const response = await getChatList()
    if (response.code === 200 && response.data) {
      chatList.value = response.data
    } else {
      ElMessage.error(response.msg || '获取聊天列表失败')
    }
  } catch (error) {
    console.error('获取聊天列表出错:', error)
    ElMessage.error('获取聊天列表失败')
  } finally {
    loadingChatList.value = false
  }
}

// 当前选中供应商的模型列表
const currentProviderModels = computed(() => {
  // 确保 providers.value 存在且是数组
  if (!providers.value || !Array.isArray(providers.value)) {
    return []
  }
  
  // 确保 selectedProvider.value 存在
  if (!selectedProvider.value) {
    return []
  }
  
  const provider = providers.value.find(p => p.name === selectedProvider.value)
  return provider && provider.models ? provider.models : []
})

// 获取供应商和模型列表
const fetchProviders = async (): Promise<void> => {
  loadingProviders.value = true
  try {
    const response = await getProviderList()
    console.log('供应商列表响应:', response)
    
    if (response.code === 200 && response.data && Array.isArray(response.data)) {
      // 过滤掉无效的供应商数据
      providers.value = response.data.filter(provider => 
        provider && 
        provider.name && 
        provider.id !== undefined &&
        Array.isArray(provider.models)
      )
      
      // 如果有有效的供应商，默认选择第一个
      if (providers.value.length > 0) {
        selectedProvider.value = providers.value[0].name
        // 默认选择第一个模型
        if (providers.value[0].models && providers.value[0].models.length > 0) {
          selectedModel.value = providers.value[0].models[0]
        }
      }
    } else {
      console.error('供应商列表数据格式错误:', response)
      ElMessage.error(response.msg || '获取供应商列表失败')
      providers.value = []
    }
  } catch (error) {
    console.error('获取供应商列表失败:', error)
    ElMessage.error('获取供应商列表失败')
    providers.value = []
  } finally {
    loadingProviders.value = false
  }
}

// 处理提供商变更
const handleProviderChange = (providerName: string) => {
  selectedProvider.value = providerName
  const provider = providers.value.find(p => p.name === providerName)
  if (provider && provider.models.length > 0) {
    selectedModel.value = provider.models[0]  // 设置为第一个模型
  } else {
    selectedModel.value = ''
  }
}

// 切换高级设置显示状态
const toggleAdvancedSettings = () => {
  showAdvancedSettings.value = !showAdvancedSettings.value
}

// 应用模板
const applyTemplate = (type: string) => {
  let promptTemplate = ''
  
  switch (type) {
    case 'general':
      promptTemplate = '你是一个智能助手，能够回答各种问题并提供有用的信息。请以友好、专业的方式与用户交流。'
      break
    case 'code':
      promptTemplate = '你是一个专业的编程助手，擅长多种编程语言和技术栈。请帮助用户解决编程问题，提供代码示例和最佳实践建议。'
      break
    case 'writing':
      promptTemplate = '你是一个专业的写作助手，能够帮助用户改进文本、提供写作建议、润色文章。请以清晰、准确的方式协助用户完成写作任务。'
      break
  }
  
  // 将模板内容设置到自定义提示词中
  newChatForm.value.systemContext = promptTemplate
  
  ElMessage.success(`已应用模板到自定义提示词`)
}



// 创建新聊天
const createNewChat = async (systemFlag = 0, systemContext = ''): Promise<void> => {
  createChatLoading.value = true
  try {
    // 准备创建聊天的参数
    const params = {
      // 保留原有的SystemFlag逻辑
      systemFlag: systemFlag || (newChatForm.value.useSystemPrompt === 1 ? 1 : 0),
      // 传递选中的角色ID
      roleId: selectedRoleId.value || newChatForm.value.roleId,
      // 传递自定义提示词（如果是自定义角色）
      systemContext: systemContext || newChatForm.value.systemContext,
      // 使用表单中的名称
      name: newChatForm.value.name.trim() || '新的对话'
    }

    await createNewChatWithParams(params)
  } finally {
    createChatLoading.value = false
  }
}

// 统一的创建聊天逻辑
const createNewChatWithParams = async (params: any): Promise<void> => {
  try {
    // 仅在开发环境打印日志
    if (import.meta.env.MODE !== 'production') {
      console.log('创建新聊天参数:', params)
    }

    const response = await createChat(params)

    if (response.code === 200 && response.data) {
      // 设置当前聊天ID
      const chatId = typeof response.data === 'object' ? response.data.ID : response.data
      currentChatId.value = chatId

      // 关闭创建对话框
      createChatDialogVisible.value = false

      // 刷新聊天列表
      await fetchChatList()

      // 创建成功后，如果没有选择供应商，使用默认供应商
      if (!selectedProvider.value && providers.value.length > 0) {
        selectedProvider.value = providers.value[0].name
        handleProviderChange(selectedProvider.value)
      }

      // 添加一条欢迎消息
      messages.value = [{
        id: generateId(),
        role: 'assistant',
        content: '欢迎使用布丁AI助手，我可以帮您回答问题、编写代码、创作内容等。请告诉我您需要什么帮助？',
        timestamp: Date.now()
      }]

      // 更新URL
      const url = new URL(window.location.href)
      url.searchParams.set('id', String(chatId))
      window.history.pushState({}, '', url.toString())

      // 滚动到底部
      await scrollToBottom()

      // 聚焦输入框
      nextTick(() => {
        const inputEl = document.querySelector('.chat-input textarea')
        if (inputEl) {
          (inputEl as HTMLTextAreaElement).focus()
        }
      })
    } else {
      ElMessage.error(response.msg || '创建聊天失败')
    }
  } catch (error) {
    console.error('创建聊天出错:', error)
    ElMessage.error('创建聊天失败')
  }
}

// 当按下Enter键时发送消息(没有按Shift)
const handleKeydown = (e: KeyboardEvent): void => {
  if (e.key === 'Enter' && !e.shiftKey) {
    e.preventDefault()
    sendMessage()
  }
}

// 缓存键定义，与src/api/chat.ts中的CACHE_KEYS保持一致
const CACHE_KEYS = {
  CHAT_LIST: 'chat_list',
  CHAT_MESSAGES: 'chat_messages', // 会拼接上chat_id
  MODEL_LIST: 'model_list' // 会拼接上agent
}

// 清除缓存并从云端重新加载数据
const refreshFromCloud = async () => {
  if (refreshing.value) return;

  refreshing.value = true;
  try {
    // 判断当前是否有选中的聊天
    if (currentChatId.value) {
      // 清除当前聊天的消息缓存
      Cache.remove(`${CACHE_KEYS.CHAT_MESSAGES}_${currentChatId.value}`);
    }

    // 清除聊天列表缓存
    Cache.remove(CACHE_KEYS.CHAT_LIST);

    // 清除模型列表缓存
    Cache.clearWithPrefix(CACHE_KEYS.MODEL_LIST);

    ElMessage.success('缓存已清除，正在重新加载数据...');

    // 重新加载数据
    await fetchChatList();

    // 如果有当前聊天，重新加载消息
    if (currentChatId.value) {
      await loadChatMessages(currentChatId.value);
    }

    ElMessage.success('数据刷新成功！');
  } catch (error) {
    console.error('刷新数据失败:', error);
    ElMessage.error('刷新数据失败，请稍后再试');
  } finally {
    refreshing.value = false;
    // 隐藏浮窗
    cacheRefreshVisible.value = false;
  }
}

// 切换刷新浮窗的显示状态
const toggleCacheRefreshWidget = () => {
  cacheRefreshVisible.value = !cacheRefreshVisible.value;
}

// 添加流式响应变量
const streamingContent = ref('');
const streamingComplete = ref(true);

// 思考相关状态变量
const streamingReasoning = ref('')  // 流式思考内容
const currentStreamingMessageId = ref<string | null>(null)  // 当前流式消息的ID
const hasReasoningContent = ref(false)  // 是否有思考内容
</script>

<template>
  <div class="chat-container">
    <!-- 侧边栏 -->
    <div class="sidebar" :class="{ 'collapsed': !sidebarExpanded }">
      <!-- 头部Logo -->
      <div class="sidebar-header">
        <img src="../assets/buding-logo.svg" alt="布丁AI" class="logo"/>
        <h1 class="app-name" v-if="sidebarExpanded">布丁AI</h1>
        <button class="toggle-sidebar" @click="sidebarExpanded = !sidebarExpanded">
          <el-icon>
            <Position/>
          </el-icon>
        </button>
      </div>

      <!-- 新对话按钮 -->
      <div class="sidebar-actions">
        <button class="new-chat-button" @click="showCreateChatDialog">
          <el-icon>
            <Plus/>
          </el-icon>
          <span v-if="sidebarExpanded">新对话</span>
        </button>
      </div>

      <!-- 历史对话列表 -->
      <div class="sidebar-content">
        <div class="chat-history">
          <!-- 今天的对话 -->
          <div class="history-group" v-if="todayChats.length > 0">
            <h3 class="history-group-title" v-if="sidebarExpanded">今天</h3>
            <div class="chat-item"
                 v-for="chat in todayChats"
                 :key="chat.ID"
                 :class="{ 'active': currentChatId === chat.ID, 'collapsed': !sidebarExpanded }"
                 @click="loadChatHistory(chat.ID)">
              <div class="chat-icon">
                <el-icon>
                  <ChatDotRound/>
                </el-icon>
              </div>
              <div class="chat-name-container" v-if="sidebarExpanded">
                <div class="chat-name">{{ chat.name || '新对话' }}</div>
                <!-- 消息数量指示器 -->
                <div class="message-count-badge" v-if="chat.message_count > 0">
                  {{ chat.message_count }}
                </div>
              </div>

              <div class="chat-actions" v-if="sidebarExpanded">
                <el-dropdown trigger="click" @command="(command: string) => handleHistoryAction(command, chat.ID)">
                  <el-icon class="more-icon">
                    <More/>
                  </el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="rename">重命名</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 本周的对话 -->
          <div class="history-group" v-if="weekChats.length > 0">
            <h3 class="history-group-title" v-if="sidebarExpanded">本周</h3>
            <div class="chat-item"
                 v-for="chat in weekChats"
                 :key="chat.ID"
                 :class="{ 'active': currentChatId === chat.ID, 'collapsed': !sidebarExpanded }"
                 @click="loadChatHistory(chat.ID)">
              <div class="chat-icon">
                <el-icon>
                  <ChatDotRound/>
                </el-icon>
              </div>
              <div class="chat-name-container" v-if="sidebarExpanded">
                <div class="chat-name">{{ chat.name || '新对话' }}</div>
                <!-- 消息数量指示器 -->
                <div class="message-count-badge" v-if="chat.message_count > 0">
                  {{ chat.message_count }}
                </div>
              </div>

              <div class="chat-actions" v-if="sidebarExpanded">
                <el-dropdown trigger="click" @command="(command: string) => handleHistoryAction(command, chat.ID)">
                  <el-icon class="more-icon">
                    <More/>
                  </el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="rename">重命名</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 本月的对话 -->
          <div class="history-group" v-if="monthChats.length > 0">
            <h3 class="history-group-title" v-if="sidebarExpanded">本月</h3>
            <div class="chat-item"
                 v-for="chat in monthChats"
                 :key="chat.ID"
                 :class="{ 'active': currentChatId === chat.ID, 'collapsed': !sidebarExpanded }"
                 @click="loadChatHistory(chat.ID)">
              <div class="chat-icon">
                <el-icon>
                  <ChatDotRound/>
                </el-icon>
              </div>
              <div class="chat-name-container" v-if="sidebarExpanded">
                <div class="chat-name">{{ chat.name || '新对话' }}</div>
                <!-- 消息数量指示器 -->
                <div class="message-count-badge" v-if="chat.message_count > 0">
                  {{ chat.message_count }}
                </div>
              </div>

              <div class="chat-actions" v-if="sidebarExpanded">
                <el-dropdown trigger="click" @command="(command: string) => handleHistoryAction(command, chat.ID)">
                  <el-icon class="more-icon">
                    <More/>
                  </el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="rename">重命名</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>

          <!-- 更早的对话 -->
          <div class="history-group" v-if="olderChats.length > 0">
            <h3 class="history-group-title" v-if="sidebarExpanded">更早</h3>
            <div class="chat-item"
                 v-for="chat in olderChats"
                 :key="chat.ID"
                 :class="{ 'active': currentChatId === chat.ID, 'collapsed': !sidebarExpanded }"
                 @click="loadChatHistory(chat.ID)">
              <div class="chat-icon">
                <el-icon>
                  <ChatDotRound/>
                </el-icon>
              </div>
              <div class="chat-name-container" v-if="sidebarExpanded">
                <div class="chat-name">{{ chat.name || '新对话' }}</div>
                <!-- 消息数量指示器 -->
                <div class="message-count-badge" v-if="chat.message_count > 0">
                  {{ chat.message_count }}
                </div>
              </div>

              <div class="chat-actions" v-if="sidebarExpanded">
                <el-dropdown trigger="click" @command="(command: string) => handleHistoryAction(command, chat.ID)">
                  <el-icon class="more-icon">
                    <More/>
                  </el-icon>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="rename">重命名</el-dropdown-item>
                      <el-dropdown-item command="delete" divided>删除</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- 用户信息和设置 -->
      <div class="sidebar-footer">
        <div class="user-info" v-if="sidebarExpanded">
          <div class="user-avatar">
            <span>{{ currentUser.nickname?.[0] || currentUser.username?.[0] || 'U' }}</span>
          </div>
          <div class="user-details">
            <div class="user-name">{{ currentUser.nickname || currentUser.username }}</div>
          </div>
        </div>
        <div class="footer-actions">
          <button class="footer-action" @click="showResetPasswordDialog" title="修改密码" v-if="sidebarExpanded">
            <el-icon>
              <Key/>
            </el-icon>
            <span>修改密码</span>
          </button>
          <button class="footer-action" @click="handleLogout" title="退出登录">
            <el-icon>
              <SwitchButton/>
            </el-icon>
            <span v-if="sidebarExpanded">退出登录</span>
          </button>
        </div>
      </div>
    </div>

    <!-- 主内容区 -->
    <div class="main-content">
      <!-- 聊天头部 -->
      <div class="chat-header">
        <h3 class="chat-title">{{
            currentChatId ? (chatList.find(c => c.ID === currentChatId)?.name || '对话') : '欢迎使用'
          }}</h3>

        <!-- 模型选择区域 - 当有选择对话时显示 -->
        <div class="model-selection-area" v-if="currentChatId">
          <!-- 提供商选择 -->
          <div class="selector-pill provider-selector">
            <el-select
                v-model="selectedProvider"
                placeholder="选择提供商"
                size="default"
                class="provider-select"
                popper-class="modern-select-dropdown"
                @change="handleProviderChange"
            >
              <el-option
                  v-for="(provider, index) in providers"
                  :key="provider.id || provider.name || index"
                  :label="provider.name || '未知供应商'"
                  :value="provider.name"
              >
                <div class="option-content">
                  <span class="option-icon">🤖</span>
                  <span class="option-name">{{ provider.name }}</span>
                </div>
              </el-option>
            </el-select>
            <div class="selected-preview">
              <span class="preview-icon">🤖</span>
              <span class="preview-name">{{ providers.find(p => p.name === selectedProvider)?.name }}</span>
            </div>
          </div>

          <!-- 模型选择 -->
          <div class="selector-pill model-selector" v-if="currentProviderModels.length > 0">
            <el-select
                v-model="selectedModel"
                placeholder="选择模型"
                size="default"
                class="model-select"
                popper-class="modern-select-dropdown"
            >
              <el-option
                  v-for="model in currentProviderModels"
                  :key="model"
                  :label="model"
                  :value="model"
              >
                <div class="option-content">
                  <span class="option-name">{{ model }}</span>
                </div>
              </el-option>
            </el-select>
            <div class="selected-preview">
              <span class="preview-name">{{ selectedModel }}</span>
            </div>
          </div>
        </div>
      </div>

      <!-- 聊天内容 -->
      <div class="chat-messages" ref="chatContainerRef" v-if="currentChatId">
        <!-- 消息区域 -->
        <div class="messages-container" ref="messagesContainer">
          <div class="messages-content" v-if="messages.length">
            <!-- 正常消息列表 -->
            <ChatMessage 
              v-for="(message, index) in messages"
              :key="message.id || index"
              :message="message"
            />
          </div>
          
          <!-- 空白对话提示 -->
          <div v-else class="empty-chat">
            <div class="empty-illustration">
              <el-icon :size="60" class="empty-icon"><ChatDotRound /></el-icon>
            </div>
            <h3>开始新的对话</h3>
            <p>在下方输入框中发送消息，开始与AI助手对话</p>
          </div>
        </div>

        <!-- 加载状态提示框 -->
        <div class="loading-indicator-container" v-if="loading">
          <div class="loading-indicator">
            <div class="loading-dots">
              <span></span>
              <span></span>
              <span></span>
            </div>
            <div class="loading-text">正在生成回复...</div>
          </div>
        </div>

        <!-- 输入区域 - 仅当选择了对话时显示 -->
        <div class="input-container" v-if="currentChatId">
          <div class="input-wrapper">
            <el-input
                v-model="inputMessage"
                type="textarea"
                :rows="1"
                :autosize="{ minRows: 1, maxRows: 6 }"
                :placeholder="loading ? '正在生成回复...' : '输入消息，按Enter发送，Shift+Enter换行'"
                @keydown="handleKeydown"
                class="chat-input"
                :disabled="loading"
            ></el-input>

            <button class="send-button" @click="sendMessage" :disabled="!inputMessage.trim() || loading">
              {{ loading ? '生成中...' : '发送' }}
              <el-icon class="send-icon" v-if="!loading">
                <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" width="16" height="16" fill="none"
                     stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <line x1="22" y1="2" x2="11" y2="13"></line>
                  <polygon points="22 2 15 22 11 13 2 9 22 2"></polygon>
                </svg>
              </el-icon>
              <el-icon class="loading-icon" v-else>
                <svg class="animate-spin" viewBox="0 0 24 24" width="16" height="16">
                  <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"
                          fill="none"></circle>
                  <path class="opacity-75" fill="currentColor"
                        d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                </svg>
              </el-icon>
            </button>
          </div>
        </div>
      </div>

      <!-- 欢迎页 - 当没有选择对话时显示 -->
      <div class="welcome-page" v-else>
        <div class="welcome-content">
          <img src="../assets/buding-logo.svg" alt="布丁AI" class="welcome-logo"/>
          <h2 class="welcome-title">欢迎使用 <span class="gradient-text">布丁AI</span></h2>
          <p class="welcome-desc">您的智能助手，随时为您解答问题、提供帮助</p>

          <div class="welcome-actions">
            <button class="start-chat-btn" @click="showCreateChatDialog">
              <el-icon>
                <Plus/>
              </el-icon>
              开始新对话
            </button>
          </div>

          <div class="feature-container">
            <div class="feature-box">
              <div class="feature-icon chat-icon">
                <el-icon>
                  <ChatDotRound/>
                </el-icon>
              </div>
              <div class="feature-info">
                <h3>智能对话</h3>
                <p>自然流畅的对话体验，支持上下文理解</p>
              </div>
            </div>

            <div class="feature-box">
              <div class="feature-icon write-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7"></path>
                  <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z"></path>
                </svg>
              </div>
              <div class="feature-info">
                <h3>创意写作</h3>
                <p>帮助您进行文案创作、内容编辑和灵感激发</p>
              </div>
            </div>

            <div class="feature-box">
              <div class="feature-icon code-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <polyline points="16 18 22 12 16 6"></polyline>
                  <polyline points="8 6 2 12 8 18"></polyline>
                </svg>
              </div>
              <div class="feature-info">
                <h3>代码助手</h3>
                <p>提供编程帮助、代码优化和技术问题解答</p>
              </div>
            </div>

            <div class="feature-box">
              <div class="feature-icon wiki-icon">
                <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none"
                     stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
                  <circle cx="12" cy="12" r="10"></circle>
                  <line x1="12" y1="16" x2="12" y2="12"></line>
                  <line x1="12" y1="8" x2="12.01" y2="8"></line>
                </svg>
              </div>
              <div class="feature-info">
                <h3>知识百科</h3>
                <p>覆盖广泛知识领域，提供准确的信息和解释</p>
              </div>
            </div>
          </div>

          <div class="usage-tips">
            <h3>使用提示</h3>
            <ul>
              <li>点击"<b>开始新对话</b>"以创建聊天</li>
              <li>选择合适的AI角色，获得更专业的回答</li>
              <li>对话历史将自动保存，方便后续继续使用</li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 对话详情弹框 -->
    <el-dialog
        v-model="chatDialogVisible"
        :title="dialogTitle"
        width="80%"
        class="chat-detail-dialog"
        destroy-on-close
        top="5vh"
    >
      <div class="dialog-content" v-if="currentDialogMessage">
        <div class="dialog-message-header">
          <div class="dialog-sender">
            <el-avatar size="medium" v-if="currentDialogMessage.role === 'user'">
              {{ currentUser.nickname?.[0] || currentUser.username?.[0] || 'U' }}
            </el-avatar>
            <el-avatar size="medium" v-else>AI</el-avatar>
            <span>{{ currentDialogMessage.role === 'user' ? '你' : '布丁AI' }}</span>
          </div>
          <div class="dialog-time">
            {{ new Date(currentDialogMessage.timestamp).toLocaleString() }}
          </div>
        </div>

        <div class="dialog-message-content">
          <div v-if="currentDialogMessage.role === 'user'" class="dialog-user-content">
              {{ currentDialogMessage.content }}
          </div>
          <div v-else class="dialog-assistant-content markdown-body"
               v-html="parseMarkdown(currentDialogMessage.content)"></div>
        </div>

        <div class="dialog-actions">
          <el-button size="small" @click="copyMessageContent">
            复制内容
          </el-button>
        </div>
      </div>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="chatDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重命名对话的弹窗 -->
    <el-dialog
        v-model="renameChatDialogVisible"
        title="重命名对话"
        width="380px"
        class="modern-dialog rename-dialog"
        destroy-on-close
    >
      <div class="dialog-content">
        <div class="input-field">
          <label>对话名称</label>
          <el-input
              v-model="renameValue"
              placeholder="请输入对话名称"
              autofocus
              maxlength="50"
              show-word-limit
          ></el-input>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="cancel-btn" @click="renameChatDialogVisible = false">取消</el-button>
          <el-button class="confirm-btn" type="primary" @click="handleRenameConfirm" :disabled="!renameValue.trim()">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重新设计的创建新对话弹窗 -->
    <el-dialog
        v-model="createChatDialogVisible"
        width="520px"
        class="enterprise-create-dialog"
        destroy-on-close
        :show-close="false"
        align-center
    >
      <!-- 自定义头部 -->
      <template #header>
        <div class="dialog-header">
          <div class="header-content">
            <div class="header-icon">
              <el-icon><ChatDotRound /></el-icon>
            </div>
            <div class="header-text">
              <h3 class="dialog-title">创建新对话</h3>
              <p class="dialog-subtitle">开始与AI助手的智能对话</p>
            </div>
          </div>
          <el-button 
              class="close-btn" 
              @click="createChatDialogVisible = false"
              :icon="Close"
              circle
              size="small"
              text
          />
        </div>
      </template>

      <div class="enterprise-dialog-content">
        <!-- 自定义设置区域 -->
        <div class="custom-section">
          <div class="form-group">
            <label class="form-label">
              <el-icon><Edit /></el-icon>
              对话名称
              <span class="optional-tag">可选</span>
            </label>
            <el-input
                v-model="newChatForm.name"
                placeholder="为这次对话起个名字..."
                maxlength="50"
                class="modern-input"
                clearable
            >
              <template #prefix>
                <el-icon class="input-icon"><ChatDotRound /></el-icon>
              </template>
            </el-input>
          </div>

          <!-- 高级设置 -->
          <div class="advanced-settings-wrapper">
            <div class="advanced-toggle" @click="toggleAdvancedSettings">
              <div class="toggle-content">
                <el-icon class="toggle-icon"><Setting /></el-icon>
                <span class="toggle-text">高级设置</span>
                <span class="toggle-subtitle">AI角色、提示词等</span>
              </div>
              <el-switch 
                v-model="showAdvancedSettings" 
                class="toggle-switch"
                @click.stop
              />
            </div>
            
            <!-- 高级设置内容 -->
            <div v-show="showAdvancedSettings" class="advanced-content">
              <!-- AI角色选择 -->
              <div class="form-group">
                <label class="form-label">
                  <el-icon><User /></el-icon>
                  AI角色类型
                </label>
                <el-select
                    v-model="selectedRoleId"
                    placeholder="选择AI角色类型"
                    class="modern-select"
                    clearable
                    filterable
                >
                  <el-option
                      v-for="role in roleList"
                      :key="role.id"
                      :label="role.name"
                      :value="role.id"
                  >
                    <div class="role-option">
                      <span class="role-emoji">{{ role.icon || '🤖' }}</span>
                      <div class="role-info">
                        <div class="role-name">{{ role.name }}</div>
                        <div class="role-desc">{{ role.describe }}</div>
                      </div>
                    </div>
                  </el-option>
                </el-select>
              </div>

              <!-- 快速模板 - 只在自定义角色时显示 -->
              <div class="form-group" v-if="isCustomRole">
                <label class="form-label">
                  <el-icon><Magic /></el-icon>
                  快速模板
                  <span class="optional-tag">可选</span>
                </label>
                <div class="template-options">
                  <el-button 
                    class="template-btn" 
                    @click="applyTemplate('general')"
                    size="small"
                  >
                    💬 通用对话
                  </el-button>
                  <el-button 
                    class="template-btn" 
                    @click="applyTemplate('code')"
                    size="small"
                  >
                    💻 代码助手
                  </el-button>
                  <el-button 
                    class="template-btn" 
                    @click="applyTemplate('writing')"
                    size="small"
                  >
                    ✍️ 写作助手
                  </el-button>
                </div>
              </div>

              <!-- 自定义提示词 -->
              <div class="form-group" v-if="selectedRoleId">
                <label class="form-label">
                  <el-icon><Document /></el-icon>
                  自定义提示词
                  <span class="optional-tag">可选</span>
                </label>
                <el-input
                    v-model="newChatForm.systemContext"
                    type="textarea"
                    :rows="4"
                    placeholder="输入自定义提示词来个性化AI的行为和回答风格..."
                    class="modern-textarea"
                />
              </div>
            </div>
          </div>
        </div>
      </div>

      <template #footer>
        <div class="enterprise-dialog-footer">
          <el-button 
              class="cancel-button" 
              @click="createChatDialogVisible = false"
              size="large"
          >
            取消
          </el-button>
          <el-button 
              class="create-button" 
              type="primary" 
              @click="createNewChat()"
              size="large"
              :loading="createChatLoading"
          >
            <el-icon v-if="!createChatLoading"><Plus /></el-icon>
            {{ createChatLoading ? '创建中...' : '创建对话' }}
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 重置密码弹窗 -->
    <el-dialog
        v-model="resetPasswordDialogVisible"
        title="重置密码"
        width="380px"
        class="modern-dialog reset-password-dialog"
        destroy-on-close
    >
      <div class="dialog-content">
        <div class="input-field">
          <label>当前密码</label>
          <el-input
              v-model="resetPasswordForm.oldPassword"
              placeholder="请输入当前密码"
              type="password"
              show-password
              autocomplete="current-password"
          ></el-input>
        </div>

        <div class="input-field">
          <label>新密码</label>
          <el-input
              v-model="resetPasswordForm.newPassword"
              placeholder="请输入新密码"
              type="password"
              show-password
              autocomplete="new-password"
          ></el-input>
        </div>

        <div class="input-field">
          <label>确认新密码</label>
          <el-input
              v-model="resetPasswordForm.confirmPassword"
              placeholder="请再次输入新密码"
              type="password"
              show-password
              autocomplete="new-password"
          ></el-input>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button class="cancel-btn" @click="resetPasswordDialogVisible = false">取消</el-button>
          <el-button
              class="confirm-btn"
              type="primary"
              @click="submitResetPassword"
              :loading="resetPasswordLoading"
          >确定
          </el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 缓存刷新浮窗 -->
    <div class="refresh-widget-trigger" @click="toggleCacheRefreshWidget">
      <el-icon>
        <Refresh/>
      </el-icon>
    </div>

    <transition name="fade">
      <div v-if="cacheRefreshVisible" class="refresh-widget">
        <div class="refresh-widget-header">
          <h3>数据刷新</h3>
          <button class="close-btn" @click="cacheRefreshVisible = false">×</button>
        </div>
        <div class="refresh-widget-content">
          <p>点击下方按钮清除本地缓存并从云端重新加载数据</p>
          <el-button
              type="primary"
              :loading="refreshing"
              @click="refreshFromCloud"
              :disabled="refreshing"
          >
            <el-icon>
              <Refresh/>
            </el-icon>
            {{ refreshing ? '刷新中...' : '刷新数据' }}
          </el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<style lang="scss" scoped>
// 定义常用颜色变量，避免重复使用硬编码颜色值
$primary-color: #6366F1;
$primary-light: rgba(99, 102, 241, 0.05);
$primary-shadow: rgba(99, 102, 241, 0.12);
$secondary-color: #8B5CF6;
$border-color: rgba(99, 102, 241, 0.1);
$gradient-bg: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);

// 定义共用的阴影效果
@mixin standard-shadow {
  box-shadow: 0 4px 16px $primary-shadow;
}

@mixin hover-shadow {
  box-shadow: 0 6px 20px rgba(99, 102, 241, 0.15);
}

// 定义共用的按钮样式
@mixin button-hover {
  transform: translateY(-2px);
  @include hover-shadow;
}

.chat-container {
  display: flex;
  height: 100vh;
  width: 100%;
  // 系统风格的浅紫蓝渐变背景
  background: linear-gradient(135deg, 
    #f8faff 0%, 
    #f3f4ff 25%, 
    #eef2ff 50%, 
    #e0e7ff 75%, 
    #ddd6fe 100%);
  position: relative;
  overflow: hidden;

  // 添加微妙的纹理效果
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background-image: 
      radial-gradient(circle at 25% 25%, rgba(99, 102, 241, 0.05) 0%, transparent 50%),
      radial-gradient(circle at 75% 75%, rgba(139, 92, 246, 0.05) 0%, transparent 50%),
      radial-gradient(rgba(99, 102, 241, 0.02) 1px, transparent 1px);
    background-size: 200px 200px, 200px 200px, 20px 20px;
    z-index: 0;
    animation: backgroundShift 20s ease-in-out infinite;
  }

  .sidebar {
    width: 240px;
    height: 100%;
    background: rgba(255, 255, 255, 0.95);
    backdrop-filter: blur(10px);
    display: flex;
    flex-direction: column;
    box-shadow: 
      0 0 30px rgba(99, 102, 241, 0.1),
      0 0 60px rgba(139, 92, 246, 0.05);
    transition: width 0.3s;
    position: relative;
    z-index: 1;
    border-right: 1px solid rgba(99, 102, 241, 0.1);

    &.collapsed {
      width: 60px;
    }

    .sidebar-header {
      display: flex;
      align-items: center;
      padding: 16px;
      border-bottom: 1px solid rgba(99, 102, 241, 0.08);

      .logo {
        width: 32px;
        height: 32px;
      }

      .app-name {
        margin-left: 12px;
        font-size: 18px;
        font-weight: 600;
        background: linear-gradient(90deg, #6366F1 0%, #8B5CF6 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
      }

      .toggle-sidebar {
        margin-left: auto;
        background: transparent;
        border: none;
        width: 32px;
        height: 32px;
        border-radius: 8px;
        color: #6366F1;
        cursor: pointer;
        transition: all 0.2s;

        &:hover {
          background-color: rgba(99, 102, 241, 0.1);
        }
      }
    }

    .sidebar-actions {
      padding: 16px;

      .new-chat-button {
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100%;
        padding: 12px;
        border-radius: 12px;
        background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
        color: white;
        border: none;
        font-weight: 600;
        cursor: pointer;
        transition: all 0.3s;
        box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25);

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 6px 16px rgba(99, 102, 241, 0.35);
        }

        .el-icon {
          margin-right: 8px;
        }
      }
    }

    .sidebar-content {
      flex: 1;
      overflow-y: auto;
      padding: 16px;

      .chat-history {
        display: flex;
        flex-direction: column;
        gap: 16px;

        .history-group-title {
          font-size: 0.85rem;
          color: #6b7280;
          margin-bottom: 8px;
          font-weight: 600;
          padding-left: 4px;
        }

        .chat-item {
          display: flex;
          align-items: center;
          padding: 10px 12px;
          border-radius: 12px;
          cursor: pointer;
          transition: all 0.2s;
          color: #4b5563;
          position: relative;

          &:hover {
            background-color: rgba(99, 102, 241, 0.08);
          }

          &.active {
            background-color: rgba(99, 102, 241, 0.12);
            color: #6366F1;
            font-weight: 500;
          }

          &.collapsed {
            justify-content: center;
            padding: 10px 0;
          }

          .chat-icon {
            width: 28px;
            height: 28px;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 16px;
            color: inherit;
          }

          .chat-name-container {
            flex: 1;
            margin-left: 10px;
            display: flex;
            align-items: center;
            min-width: 0; /* 防止内容溢出 */
          }

          .message-count-badge {
            width: 18px;
            height: 18px;
            border-radius: 50%; /* 完全圆形 */
            background-color: #6366F1;
            color: white;
            font-size: 0.7rem;
            font-weight: 500;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-left: 8px;
            box-shadow: 0 2px 4px rgba(99, 102, 241, 0.25);
            flex-shrink: 0; /* 防止徽章被压缩 */
          }

          .chat-name {
            font-size: 0.9rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
            flex: 1;
          }

          .chat-actions {
            opacity: 0;
            transition: opacity 0.2s;

            .more-icon {
              width: 24px;
              height: 24px;
              color: #6b7280;
              cursor: pointer;

              &:hover {
                color: #6366F1;
              }
            }
          }

          &:hover .chat-actions {
            opacity: 1;
          }
        }
      }

      &::-webkit-scrollbar {
        width: 4px;
      }

      &::-webkit-scrollbar-track {
        background: transparent;
      }

      &::-webkit-scrollbar-thumb {
        background-color: rgba(99, 102, 241, 0.2);
        border-radius: 2px;
      }
    }

    .sidebar-footer {
      padding: 16px;
      border-top: 1px solid rgba(99, 102, 241, 0.08);

      .user-info {
        display: flex;
        align-items: center;
        margin-bottom: 12px;

        .user-avatar {
          width: 36px;
          height: 36px;
          border-radius: 50%;
          background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
          color: white;
          display: flex;
          align-items: center;
          justify-content: center;
          font-weight: 600;
          font-size: 14px;
          box-shadow: 0 2px 8px rgba(99, 102, 241, 0.25);
        }

        .user-details {
          margin-left: 10px;

          .user-name {
            font-size: 0.9rem;
            font-weight: 500;
            color: #4b5563;
          }
        }
      }

      .footer-actions {
        display: flex;
        flex-direction: column;
        gap: 8px;

        .footer-action {
          display: flex;
          align-items: center;
          gap: 8px;
          padding: 8px 12px;
          border-radius: 8px;
          border: none;
          background: transparent;
          color: #4b5563;
          font-size: 0.9rem;
          cursor: pointer;
          transition: all 0.2s;

          &:hover {
            background-color: rgba(99, 102, 241, 0.08);
            color: #6366F1;
          }
        }
      }
    }
  }

  .main-content {
    flex: 1;
    display: flex;
    flex-direction: column;
    background: rgba(255, 255, 255, 0.3);
    backdrop-filter: blur(5px);
    position: relative;
    z-index: 1;

    .chat-header {
      padding: 16px 24px;
      display: flex;
      align-items: center;
      justify-content: space-between;
      border-bottom: 1px solid rgba(99, 102, 241, 0.08);
      background-color: rgba(255, 255, 255, 0.85);
      backdrop-filter: blur(10px);
      z-index: 5;
      box-shadow: 0 1px 8px rgba(0, 0, 0, 0.03);

      .chat-title {
        margin: 0;
        font-size: 1.2rem;
        font-weight: 600;
        color: #374151;
      }

      .model-selection-area {
        display: flex;
        align-items: center;
        gap: 12px;

        .provider-selector {
          display: flex;
          align-items: center;
          gap: 8px;
          position: relative;

          .provider-select {
            width: 120px;
            height: 36px;
            border-radius: 18px;
            border: 1px solid rgba(99, 102, 241, 0.15);
            background-color: white;
            padding: 0 16px;
            font-size: 0.9rem;
            color: #64748b;
            transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
            position: relative;
            z-index: 1;

            &:hover {
              border-color: rgba(99, 102, 241, 0.3);
            }

            &.is-focus {
              border-color: $primary-color;
              box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
            }

            .el-input__inner {
              color: #334155;
              font-weight: 500;
            }
          }

          .select-decoration {
            font-size: 1.2rem;
            color: #94a3b8;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            pointer-events: none;
          }
        }

        .model-selector {
          min-width: 140px;
          position: relative;
          display: flex;
          align-items: center;

          .model-select {
            width: 100%;

            :deep(.el-input__wrapper) {
              border-radius: 18px;
              background-color: white;
              box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
              border: 1px solid rgba(99, 102, 241, 0.15);
              padding: 4px 12px;
              position: relative;
              z-index: 1;

              &:hover {
                border-color: rgba(99, 102, 241, 0.3);
              }

              &.is-focus {
                border-color: $primary-color;
                box-shadow: 0 0 0 2px rgba(99, 102, 241, 0.1);
              }

              .el-input__inner {
                color: #334155;
                font-weight: 500;
              }
            }
          }

          .select-decoration {
            font-size: 1.2rem;
            color: #94a3b8;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            pointer-events: none;
          }
        }
      }
    }

    .chat-messages {
      flex: 1;
      overflow: hidden;
      display: flex;
      flex-direction: column;
      background: linear-gradient(to right, #f8f9ff, #f9fbff);

      .messages-container {
        flex: 1;
        overflow-y: auto;
        padding: 24px 20px;
        
        &::-webkit-scrollbar {
          width: 6px;
        }
        
        &::-webkit-scrollbar-track {
          background: transparent;
        }
        
        &::-webkit-scrollbar-thumb {
          background-color: rgba(99, 102, 241, 0.2);
          border-radius: 3px;
        }
        
        .messages-content {
          max-width: 900px;
          width: 92%;
          margin: 0 auto;
          display: flex;
          flex-direction: column;
          gap: 18px;
        }
      }

      .message-item {
        position: relative;
      }

      .empty-chat {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        height: 100%;
        padding: 20px;
        color: #6b7280;
        text-align: center;
        
        .empty-illustration {
          width: 120px;
          height: 120px;
          background-color: rgba(99, 102, 241, 0.05);
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-bottom: 24px;
          
          .empty-icon {
            color: #818cf8;
          }
        }
        
        h3 {
          font-size: 1.25rem;
          font-weight: 500;
          color: #4b5563;
          margin: 0 0 12px;
        }
        
        p {
          font-size: 0.95rem;
          max-width: 360px;
          line-height: 1.5;
          margin: 0;
        }
      }
    }

    .input-container {
      padding: 16px;
      background-color: rgba(255, 255, 255, 0.85);
      border-top: 1px solid rgba(99, 102, 241, 0.08);
      backdrop-filter: blur(10px);
      position: relative;
      z-index: 5;
      box-shadow: 0 -1px 8px rgba(0, 0, 0, 0.03);

      .input-wrapper {
        max-width: 900px;
        width: 92%;
        margin: 0 auto;
        display: flex;
        align-items: center;
        gap: 12px;
        position: relative;
        background-color: white;
        border-radius: 24px;
        box-shadow: 0 4px 20px rgba(99, 102, 241, 0.1);
        padding: 12px 16px;
        border: 1px solid rgba(99, 102, 241, 0.15);
        transition: all 0.3s ease;

        &:hover, &:focus-within {
          box-shadow: 0 6px 24px rgba(99, 102, 241, 0.15);
          border-color: rgba(99, 102, 241, 0.3);
          transform: translateY(-1px);
        }

        .chat-input {
          flex: 1;

          :deep(.el-textarea__inner) {
            border: none;
            box-shadow: none;
            padding: 8px 8px;
            font-size: 0.95rem;
            line-height: 1.5;
            background: transparent;
            resize: none;
            max-height: 120px;

            &:focus {
              outline: none;
              box-shadow: none;
            }

            &::placeholder {
              color: #a0aec0;
            }
          }
        }

        .send-button {
          display: flex;
          align-items: center;
          justify-content: center;
          gap: 6px;
          padding: 10px 20px;
          border-radius: 18px;
          background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
          color: white;
          font-weight: 500;
          border: none;
          transition: all 0.3s;
          white-space: nowrap;
          box-shadow: 0 3px 10px rgba(99, 102, 241, 0.2);

          &:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(99, 102, 241, 0.3);
          }

          &:disabled {
            opacity: 0.6;
            cursor: not-allowed;
          }

          .send-icon {
            font-size: 16px;
          }
        }
      }
    }
  }
}

/* 现代化的对话框样式 - 添加高度限制 */
:deep(.modern-dialog) {
  .el-dialog {
    border-radius: 36px;
    overflow: hidden;
    box-shadow: 0 15px 55px rgba(99, 102, 241, 0.12), 0 10px 20px rgba(99, 102, 241, 0.06);
    border: none;
    transform: translateY(0);
    transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), box-shadow 0.3s ease;
    /* 添加最大高度限制 */
    max-height: 85vh;
    display: flex;
    flex-direction: column;

    &:hover {
      box-shadow: 0 25px 65px rgba(99, 102, 241, 0.15), 0 12px 30px rgba(99, 102, 241, 0.08);
    }
  }

  .el-dialog__header {
    padding: 16px 24px 14px;
    background: linear-gradient(to right, $primary-light, rgba(139, 92, 246, 0.05));
    border-bottom: 1px solid $border-color;
    border-radius: 36px 36px 0 0;
    margin: 0;
    /* 确保头部不会被压缩 */
    flex-shrink: 0;

    .el-dialog__title {
      font-weight: 600;
      background: linear-gradient(90deg, $primary-color 0%, $secondary-color 100%);
      -webkit-background-clip: text;
      -webkit-text-fill-color: transparent;
      background-clip: text;
    }

    .el-dialog__headerbtn {
      top: 16px;
      right: 24px;

      .el-dialog__close {
        color: $primary-color;

        &:hover {
          color: #4F46E5;
        }
      }
    }
  }

  .el-dialog__body {
    padding: 20px 24px;
    /* 让内容区域可滚动 */
    overflow-y: auto;
    flex: 1;
    min-height: 0;

    /* 自定义滚动条样式 */
    &::-webkit-scrollbar {
      width: 6px;
    }

    &::-webkit-scrollbar-track {
      background: #f1f5f9;
      border-radius: 3px;
    }

    &::-webkit-scrollbar-thumb {
      background: #cbd5e1;
      border-radius: 3px;
      transition: background 0.2s ease;
    }

    &::-webkit-scrollbar-thumb:hover {
      background: #94a3b8;
    }

    .dialog-content {
      .input-field {
        margin-bottom: 16px;

        label {
          display: block;
          font-weight: 500;
          margin-bottom: 8px;
          color: #4b5563;

          .optional-label {
            font-weight: normal;
            color: #94a3b8;
            font-size: 0.85em;
          }
        }
      }

      .system-prompt-switch {
        display: flex;
        align-items: center;
        margin-bottom: 16px;
        padding: 12px;
        background-color: rgba(99, 102, 241, 0.05);
        border-radius: 12px;

        .switch-label {
          margin-left: 12px;
          font-weight: 500;
          color: #4b5563;

          .tip {
            font-weight: normal;
            color: #94a3b8;
            font-size: 0.85em;
          }
        }
      }

      .prompt-selection {
        margin-top: 16px;

        .role-instruction {
          margin-bottom: 12px;
          font-weight: 500;
          color: #4b5563;
        }

        .role-selector {
          margin-bottom: 16px;
        }

        .prompt-editor {
          margin-top: 16px;

          .editor-header {
            margin-bottom: 8px;

            label {
              font-weight: 500;
              color: #4b5563;
            }
          }
        }
      }
    }
  }

  .el-dialog__footer {
    padding: 16px 24px 20px;
    border-top: 1px solid $border-color;
    /* 确保底部按钮区域不会被压缩 */
    flex-shrink: 0;

    .dialog-footer {
      display: flex;
      justify-content: flex-end;
      gap: 12px;

      .cancel-btn, .cancel-button {
        background-color: white;
        border: 1px solid rgba(99, 102, 241, 0.2);
        color: $primary-color;
        transition: all 0.3s;

        &:hover {
          background-color: $primary-light;
          border-color: $primary-color;
        }
      }

      .confirm-btn, .confirm-button {
        background: $gradient-bg;
        border: none;
        box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25);
        transition: all 0.3s;

        &:hover {
          @include button-hover;
        }
      }
    }
  }
}

:deep(.system-prompt-switch) {
  .el-switch__core {
    border-color: rgba(99, 102, 241, 0.3);
    background-color: rgba(99, 102, 241, 0.1);
  }

  &.is-checked {
    .el-switch__core {
      background: $gradient-bg;
      border-color: transparent;
    }
  }
}

:deep(.message-dialog) {
  .el-dialog {
    max-width: 850px;
    width: 90%;
  }
}

:deep(.el-dropdown-menu) {
  border-radius: 12px;
  padding: 6px;
  box-shadow: 0 8px 24px rgba(99, 102, 241, 0.15), 0 4px 12px rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(99, 102, 241, 0.1);

  .el-dropdown-menu__item {
    border-radius: 8px;
    margin: 2px 0;
    padding: 8px 16px;

    &:hover {
      background-color: rgba(99, 102, 241, 0.08);
      color: #6366F1;
    }

    &.is-disabled {
      opacity: 0.5;
    }
  }
}

/* 输入区域的样式改进 */
.input-container {
  padding: 12px 16px;
  background-color: rgba(255, 255, 255, 0.7);
  border-top: 1px solid rgba(99, 102, 241, 0.08);
  backdrop-filter: blur(8px);
  position: relative;
  z-index: 5;

  .input-wrapper {
    max-width: 1280px;
    width: 95%;
    margin: 0 auto;
    display: flex;
    align-items: center;
    gap: 12px;
    position: relative;
    background-color: white;
    border-radius: 16px;
    @include standard-shadow;
    padding: 10px 16px;
    border: 1px solid $border-color;
    transition: all 0.3s ease;

    &:hover, &:focus-within {
      @include hover-shadow;
      border-color: rgba(99, 102, 241, 0.25);
    }

    .chat-input {
      flex: 1;

      :deep(.el-textarea__inner) {
        border: none;
        box-shadow: none;
        padding: 8px 0;
        font-size: 1rem;
        line-height: 1.5;
        background: transparent;
        resize: none;
        max-height: 120px;

        &:focus {
          outline: none;
          box-shadow: none;
        }
      }
    }

    .send-button {
      display: flex;
      align-items: center;
      justify-content: center;
      gap: 6px;
      padding: 8px 16px;
      border-radius: 12px;
      background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
      color: white;
      font-weight: 600;
      border: none;
      transition: all 0.3s;
      white-space: nowrap;

      &:hover:not(:disabled) {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(99, 102, 241, 0.25);
      }

      &:disabled {
        opacity: 0.6;
        cursor: not-allowed;
      }

      .send-icon {
        font-size: 16px;
      }
    }
  }
}

/* 响应式设计增强 */
@media screen and (max-width: 1400px) {
  .main-content {
    .messages-container .messages-content,
    .input-container .input-wrapper {
      max-width: 1100px;
      width: 96%;
    }
  }
}

/* 企业级角色选择器样式 */
.enterprise-role-selector {
  margin-bottom: 24px;
}

/* 角色选择下拉框选项样式 */
.enterprise-role-option {
  padding: 0 !important;
  height: auto !important;
  line-height: normal !important;
}

.role-option-content {
  padding: 16px;
  transition: all 0.2s ease;
}

.role-option-content:hover {
  background-color: #f8f9fa;
}

.role-header {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.role-icon-wrapper {
  width: 40px;
  height: 40px;
  border-radius: 8px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  flex-shrink: 0;
}

.role-icon {
  font-size: 18px;
  color: white;
}

.role-info {
  flex: 1;
  min-width: 0;
}

.role-title-line {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 6px;
}

.role-name {
  font-weight: 600;
  font-size: 15px;
  color: #1f2937;
  margin-right: 8px;
}

.role-type-badge {
  padding: 3px 8px;
  border-radius: 12px;
  font-size: 11px;
  font-weight: 500;
  text-transform: uppercase;
  letter-spacing: 0.5px;
}

.badge-general {
  background-color: #dcfce7;
  color: #16a34a;
}

.badge-professional {
  background-color: #dbeafe;
  color: #2563eb;
}

.badge-creative {
  background-color: #fef3c7;
  color: #d97706;
}

.badge-custom {
  background-color: #f3f4f6;
  color: #6b7280;
}

.role-description {
  font-size: 13px;
  color: #6b7280;
  line-height: 1.5;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 选中角色预览 */
.selected-role-preview {
  margin-top: 12px;
  padding: 12px 16px;
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-radius: 8px;
  border: 1px solid #0ea5e9;
}

.preview-header {
  display: flex;
  align-items: center;
  gap: 6px;
  margin-bottom: 8px;
}

.preview-icon {
  color: #0ea5e9;
  font-size: 14px;
}

.preview-title {
  font-size: 12px;
  color: #0369a1;
  font-weight: 500;
}

.preview-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.selected-role-name {
  font-weight: 600;
  color: #0c4a6e;
  font-size: 14px;
}

.info-icon {
  color: #0ea5e9;
  cursor: help;
  transition: color 0.2s ease;
}

.info-icon:hover {
  color: #0369a1;
}

/* 企业级创建对话弹窗样式 */
.enterprise-create-dialog {
  --primary-color: #6366f1;
  --primary-light: #818cf8;
  --primary-lighter: #c7d2fe;
  --text-primary: #1f2937;
  --text-secondary: #6b7280;
  --text-tertiary: #9ca3af;
  --border-color: #e5e7eb;
  --bg-light: #f9fafb;
  --success-color: #10b981;
  --radius: 12px;
  --shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

:deep(.enterprise-create-dialog) {
  .el-dialog {
    border-radius: var(--radius);
    box-shadow: var(--shadow);
    border: 1px solid var(--border-color);
    overflow: hidden;
  }

  .el-dialog__header {
    padding: 0;
    margin: 0;
  }

  .el-dialog__body {
    padding: 0;
  }

  .el-dialog__footer {
    padding: 0;
  }
}

/* 对话框头部 */
.dialog-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24px 32px;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
}

.header-content {
  display: flex;
  align-items: center;
  gap: 16px;
}

.header-icon {
  width: 48px;
  height: 48px;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
}

.dialog-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  line-height: 1.2;
}

.dialog-subtitle {
  margin: 4px 0 0 0;
  font-size: 14px;
  opacity: 0.9;
  line-height: 1.2;
}

.close-btn {
  color: white !important;
  background: rgba(255, 255, 255, 0.1) !important;
  border: 1px solid rgba(255, 255, 255, 0.2) !important;
}

.close-btn:hover {
  background: rgba(255, 255, 255, 0.2) !important;
}

/* 对话框内容 */
.enterprise-dialog-content {
  padding: 32px;
}



/* 自定义设置区域 */
.custom-section {
  .form-group {
    margin-bottom: 24px;
  }

  .form-label {
    display: flex;
    align-items: center;
    gap: 8px;
    margin-bottom: 8px;
    font-size: 14px;
    font-weight: 500;
    color: var(--text-primary);
  }

  .optional-tag {
    background: var(--primary-lighter);
    color: var(--primary-color);
    padding: 2px 8px;
    border-radius: 4px;
    font-size: 12px;
    font-weight: 400;
    margin-left: auto;
  }
}

/* 现代化输入框 */
.modern-input :deep(.el-input__wrapper) {
  border-radius: 8px;
  border: 2px solid var(--border-color);
  transition: all 0.3s ease;
  padding: 12px 16px;
}

.modern-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary-light);
}

.modern-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

.input-icon {
  color: var(--text-tertiary);
}

/* 高级设置 */
.advanced-settings-wrapper {
  margin-top: 24px;
}

.advanced-toggle {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 20px;
  border: 2px solid var(--border-color);
  border-radius: var(--radius);
  background: white;
  cursor: pointer;
  transition: all 0.3s ease;
  margin-bottom: 16px;
}

.advanced-toggle:hover {
  border-color: var(--primary-color);
  background: var(--bg-light);
}

.toggle-content {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.toggle-icon {
  color: var(--primary-color);
  font-size: 18px;
}

.toggle-text {
  font-size: 16px;
  font-weight: 600;
  color: var(--text-primary);
}

.toggle-subtitle {
  font-size: 14px;
  color: var(--text-secondary);
  margin-left: 8px;
}

.toggle-switch {
  margin-left: 16px;
}

.advanced-content {
  padding: 20px;
  border: 1px solid var(--border-color);
  border-radius: var(--radius);
  background: var(--bg-light);
  margin-bottom: 16px;
}

/* 模板选项样式 */
.template-options {
  display: flex;
  gap: 8px;
  flex-wrap: wrap;
}

.template-btn {
  border-radius: 6px;
  border: 1px solid var(--border-color);
  background: white;
  color: var(--text-primary);
  font-size: 13px;
  padding: 8px 12px;
  transition: all 0.2s ease;
}

.template-btn:hover {
  border-color: var(--primary-color);
  color: var(--primary-color);
  background: rgba(99, 102, 241, 0.05);
}

/* 角色选项 */
.role-option {
  display: flex;
  align-items: center;
  gap: 12px;
  width: 100%;
}

.role-emoji {
  font-size: 20px;
  width: 32px;
  text-align: center;
}

.role-info {
  flex: 1;
}

.role-name {
  font-weight: 500;
  color: var(--text-primary);
  margin-bottom: 2px;
}

.role-desc {
  font-size: 12px;
  color: var(--text-secondary);
  line-height: 1.3;
}

/* 现代化文本域 */
.modern-textarea :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 2px solid var(--border-color);
  transition: all 0.3s ease;
  font-family: inherit;
  resize: vertical;
}

.modern-textarea :deep(.el-textarea__inner):hover {
  border-color: var(--primary-light);
}

.modern-textarea :deep(.el-textarea__inner):focus {
  border-color: var(--primary-color);
  box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.1);
}

/* 对话框底部 */
.enterprise-dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 24px 32px;
  background: var(--bg-light);
  border-top: 1px solid var(--border-color);
}

.cancel-button {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
}

.create-button {
  padding: 12px 24px;
  border-radius: 8px;
  font-weight: 500;
  background: var(--primary-color);
  border-color: var(--primary-color);
}

.create-button:hover {
  background: var(--primary-light);
  border-color: var(--primary-light);
}

/* 响应式设计 */
@media (max-width: 768px) {
  :deep(.enterprise-create-dialog .el-dialog) {
    width: 95% !important;
    margin: 5vh auto;
  }

  .dialog-header {
    padding: 20px 24px;
  }

  .enterprise-dialog-content {
    padding: 24px;
  }

  .enterprise-dialog-footer {
    padding: 20px 24px;
    flex-direction: column;
  }

  .cancel-button,
  .create-button {
    width: 100%;
  }

  .quick-option {
    padding: 16px;
  }

  .option-icon {
    width: 48px;
    height: 48px;
    font-size: 28px;
  }
}

/* 响应式优化 */
@media screen and (max-width: 768px) {
  :deep(.enterprise-create-dialog) {
    .el-dialog {
      width: 95% !important;
      max-width: 480px;
    }
  }

  .enterprise-dialog-content {
    padding: 20px;
  }

  .dialog-header {
    padding: 20px 24px 16px;

    .header-icon {
      width: 40px;
      height: 40px;
      font-size: 18px;
    }

    .header-text .dialog-title {
      font-size: 18px;
    }
  }

  .enterprise-dialog-footer {
    padding: 16px 20px 20px;
    flex-direction: column;

    .cancel-button,
    .create-button {
      width: 100%;
    }
  }
}

/* 优化自定义提示词区域，减少占用空间 */
.custom-prompt-section {
  margin-top: 20px;
  padding: 20px;
  background: linear-gradient(135deg, #fafbfc 0%, #f8fafc 100%);
  border-radius: 12px;
  border: 1px solid #e2e8f0;
  box-shadow: 0 1px 3px rgba(0, 0, 0, 0.05);
}

.section-header {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  margin-bottom: 16px; /* 减少间距 */
}

.header-left {
  display: flex;
  align-items: flex-start;
  gap: 12px;
}

.header-icon {
  width: 36px;
  height: 36px;
  border-radius: 8px;
  background: linear-gradient(135deg, #8b5cf6 0%, #a855f7 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 16px;
}

.header-text {
  flex: 1;
}

.section-title {
  margin: 0 0 4px 0;
  font-size: 16px;
  font-weight: 600;
  color: #1f2937;
}

.section-subtitle {
  margin: 0;
  font-size: 13px;
  color: #6b7280;
}

.help-icon {
  color: #9ca3af;
  cursor: help;
  transition: color 0.2s ease;
  font-size: 16px;
}

.help-icon:hover {
  color: #6b7280;
}

.prompt-editor-container {
  position: relative;
}

/* 优化提示词输入框高度 */
.prompt-textarea :deep(.el-textarea__inner) {
  border-radius: 8px;
  border: 2px solid #e5e7eb;
  font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
  font-size: 13px;
  line-height: 1.6;
  padding: 16px;
  background-color: #ffffff;
  transition: border-color 0.2s ease;
  /* 减少默认行数，节省空间 */
  min-height: 120px !important;
  resize: vertical;
}

.prompt-textarea :deep(.el-textarea__inner):focus {
  border-color: #8b5cf6;
  box-shadow: 0 0 0 3px rgba(139, 92, 246, 0.1);
}

/* 提示词模板 */
.prompt-templates {
  margin-top: 20px;
}

.templates-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 12px;
}

.templates-title {
  font-size: 14px;
  font-weight: 600;
  color: #374151;
}

.templates-subtitle {
  font-size: 12px;
  color: #9ca3af;
}

/* 优化模板网格布局 */
.template-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(180px, 1fr)); /* 减少最小宽度 */
  gap: 10px; /* 减少间距 */
  max-height: 200px; /* 限制模板区域高度 */
  overflow-y: auto;
}

.template-card {
  padding: 10px; /* 减少内边距 */
  border: 1px solid #e5e7eb;
  border-radius: 8px;
  background-color: #ffffff;
  cursor: pointer;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  gap: 8px; /* 减少间距 */
}

.template-card:hover {
  border-color: #8b5cf6;
  background-color: #faf5ff;
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(139, 92, 246, 0.15);
}

.template-icon {
  font-size: 20px;
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f3f4f6;
  border-radius: 6px;
}

.template-info {
  flex: 1;
}

.template-name {
  font-size: 13px;
  font-weight: 600;
  color: #374151;
  margin-bottom: 2px;
}

.template-desc {
  font-size: 11px;
  color: #9ca3af;
  line-height: 1.3;
}

/* 下拉框弹出层样式 */
:deep(.role-selector-dropdown) {
  border-radius: 12px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
  border: 1px solid #e5e7eb;
  overflow: hidden;
}

:deep(.role-selector-dropdown .el-select-dropdown__item) {
  height: auto;
  padding: 0;
}

/* 响应式优化 - 移动端 */
@media screen and (max-width: 768px) {
  :deep(.create-chat-dialog) {
    .el-dialog {
      width: 95% !important;
      max-width: 400px;
      max-height: 90vh;
    }

    .el-dialog__body {
      padding: 16px 20px;
      max-height: calc(90vh - 100px);
    }
  }

  .custom-prompt-section {
    padding: 16px;
    margin-top: 16px;
  }

  .template-grid {
    grid-template-columns: 1fr;
    max-height: 150px;
  }

  .prompt-textarea :deep(.el-textarea__inner) {
    min-height: 100px !important;
  }
}

@media screen and (max-width: 480px) {
  .section-header {
    flex-direction: column;
    gap: 12px;
  }
}

/* 为模板区域添加滚动条样式 */
.template-grid::-webkit-scrollbar {
  width: 4px;
}

.template-grid::-webkit-scrollbar-track {
  background: #f1f5f9;
  border-radius: 2px;
}

.template-grid::-webkit-scrollbar-thumb {
  background: #cbd5e1;
  border-radius: 2px;
}

.template-grid::-webkit-scrollbar-thumb:hover {
  background: #94a3b8;
}

/* 针对创建新对话对话框的响应式优化 */
@media screen and (max-width: 480px) {
  .system-prompt-switch {
    flex-direction: column;
    align-items: flex-start;

    .switch-label {
      margin-left: 0;
      margin-top: 8px;
    }
  }

  .model-selection {
    flex-direction: column;
  }

  // 消息气泡在小屏幕上的优化
  .messages-content {
    .message-bubble {
      padding: 12px 14px;
      max-width: 85%;
    }
  }

  // 输入框在小屏幕上的优化
  .input-wrapper {
    padding: 10px 12px !important;

    .send-btn {
      width: 38px !important;
      height: 38px !important;
    }
  }
}

/* 添加动画效果，提升用户体验 */
@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

.message-wrapper {
  animation: fadeIn 0.3s ease-out;
}

/* 优化对话框过渡效果 */
:deep(.el-dialog) {
  transition: transform 0.3s cubic-bezier(0.34, 1.56, 0.64, 1), opacity 0.3s ease;
}

/* 降低CSS选择器复杂度，提高渲染性能 */
.message-bubble {
  border-radius: 16px;
}

.role-card {
  height: 100%;
}

/* 针对小屏幕设备的优化 */
@media screen and (max-width: 768px) {
  .chat-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
    padding: 12px 16px;

    .model-selection-area {
      width: 100%;

      .provider-selector, .model-selector {
        flex: 1;
      }

      .provider-selector .provider-select,
      .model-selector .model-select {
        width: 100%;
      }
    }
  }
}

/* 新的现代化选择器样式 */
.model-selection-area {
  display: flex;
  align-items: center;
  gap: 12px;

  .selector-pill {
    position: relative;
    background-color: white;
    border-radius: 20px;
    box-shadow: 0 3px 10px rgba(99, 102, 241, 0.1);
    border: 1px solid rgba(99, 102, 241, 0.1);
    transition: all 0.3s ease;
    overflow: hidden;
    min-width: 150px;

    &:hover {
      box-shadow: 0 4px 15px rgba(99, 102, 241, 0.15);
      border-color: rgba(99, 102, 241, 0.2);
      transform: translateY(-1px);
    }

    .selected-preview {
      position: absolute;
      top: 0;
      left: 0;
      right: 0;
      bottom: 0;
      display: flex;
      align-items: center;
      padding: 0 16px;
      pointer-events: none;
      color: #4b5563;
      font-weight: 500;

      .preview-icon {
        margin-right: 8px;
        font-size: 1.1rem;
      }

      .preview-name {
        font-size: 0.95rem;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }

    .provider-select, .model-select {
      width: 100%;
      opacity: 0;
      cursor: pointer;
      height: 40px;

      :deep(.el-input__wrapper) {
        box-shadow: none !important;
        background: transparent;
      }
    }

    &.provider-selector {
      min-width: 120px;
    }

    &.model-selector {
      min-width: 180px;
      flex: 1;
    }
  }
}

:deep(.model-select-dropdown) {
  /* 移除旧样式以避免冲突 */
}

:deep(.provider-select-dropdown), :deep(.model-select-dropdown) {
  /* 移除旧样式以避免冲突 */
}

/* 新的下拉菜单样式 */
:deep(.modern-select-dropdown) {
  border-radius: 14px;
  border: none;
  box-shadow: 0 10px 25px rgba(99, 102, 241, 0.15), 0 5px 10px rgba(99, 102, 241, 0.1);
  padding: 8px;
  overflow: hidden;

  .el-scrollbar__wrap {
    margin-right: 0 !important;
  }

  .el-select-dropdown__item {
    border-radius: 10px;
    padding: 10px 14px;
    margin: 2px 0;
    transition: all 0.2s ease;

    &.selected {
      color: $primary-color;
      font-weight: 600;
      background: linear-gradient(to right, rgba(99, 102, 241, 0.1), rgba(139, 92, 246, 0.1));
    }

    &:hover {
      background-color: rgba(99, 102, 241, 0.05);
      transform: translateX(2px);
    }

    .option-content {
      display: flex;
      align-items: center;
      gap: 8px;

      .option-icon {
        font-size: 1.1rem;
      }

      .option-name {
        font-size: 0.95rem;
        font-weight: 500;
      }
    }
  }
}

/* 媒体查询优化 */
@media screen and (max-width: 768px) {
  .model-selection-area {
    .selector-pill {
      &.provider-selector {
        min-width: 100px;
      }

      &.model-selector {
        min-width: 0;
      }
    }
  }
}

.welcome-page {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f8f9ff;

  .welcome-content {
    max-width: 800px;
    text-align: center;
    padding: 40px 20px;

    .welcome-logo {
      width: 64px;
      height: 64px;
      border-radius: 14px;
      margin-bottom: 16px;
      box-shadow: 0 4px 12px rgba(99, 102, 241, 0.15);
    }

    .welcome-title {
      font-size: 1.8rem;
      margin-bottom: 8px;
      font-weight: 600;

      .gradient-text {
        background: linear-gradient(135deg, $primary-color 0%, $secondary-color 100%);
        -webkit-background-clip: text;
        -webkit-text-fill-color: transparent;
        background-clip: text;
        color: transparent;
      }
    }

    .welcome-desc {
      font-size: 1rem;
      color: #6b7280;
      margin-bottom: 24px;
    }

    .welcome-actions {
      margin-bottom: 32px;

      .start-chat-btn {
        padding: 10px 20px;
        border-radius: 12px;
        background: $gradient-bg;
        color: white;
        border: none;
        font-size: 1rem;
        font-weight: 500;
        display: inline-flex;
        align-items: center;
        gap: 6px;
        transition: all 0.3s;
        box-shadow: 0 4px 12px rgba(99, 102, 241, 0.2);

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 6px 16px rgba(99, 102, 241, 0.3);
        }

        .el-icon {
          font-size: 1rem;
        }
      }
    }

    .feature-container {
      display: flex;
      flex-direction: column;
      gap: 12px;
      margin-bottom: 24px;
      max-width: 500px;
      margin-left: auto;
      margin-right: auto;

      .feature-box {
        display: flex;
        text-align: left;
        padding: 16px;
        border-radius: 12px;
        background-color: white;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
        transition: all 0.2s ease;
        align-items: center;

        &:hover {
          transform: translateY(-2px);
          box-shadow: 0 4px 12px rgba(99, 102, 241, 0.1);
        }

        .feature-icon {
          width: 40px;
          height: 40px;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 10px;
          background: rgba(99, 102, 241, 0.1);
          color: $primary-color;
          margin-right: 16px;
          flex-shrink: 0;

          &.chat-icon {
            background-color: rgba(99, 102, 241, 0.1);
            color: $primary-color;
          }

          &.write-icon {
            background-color: rgba(236, 72, 153, 0.1);
            color: #ec4899;
          }

          &.code-icon {
            background-color: rgba(45, 212, 191, 0.1);
            color: #2dd4bf;
          }

          &.wiki-icon {
            background-color: rgba(251, 146, 60, 0.1);
            color: #fb923c;
          }
        }

        .feature-info {
          flex: 1;

          h3 {
            font-size: 1rem;
            font-weight: 600;
            margin: 0 0 4px 0;
            color: #374151;
          }

          p {
            font-size: 0.85rem;
            color: #6b7280;
            margin: 0;
            line-height: 1.4;
          }
        }
      }
    }

    .usage-tips {
      background-color: #ffffff;
      border-radius: 12px;
      padding: 16px 20px;
      text-align: left;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
      max-width: 500px;
      margin: 0 auto;

      h3 {
        font-size: 1rem;
        margin-top: 0;
        margin-bottom: 10px;
        color: #374151;
        font-weight: 600;
      }

      ul {
        margin: 0;
        padding-left: 18px;

        li {
          margin-bottom: 6px;
          color: #6b7280;
          font-size: 0.85rem;

          &:last-child {
            margin-bottom: 0;
          }
        }
      }
    }
  }
}

.input-wrapper {
  .chat-input {
    &.is-disabled {
      :deep(.el-textarea__inner) {
        background-color: transparent;
        cursor: not-allowed;
        color: #6b7280;

        &::placeholder {
          color: #6366F1;
          opacity: 0.8;
        }
      }
    }
  }

  .send-button {
    .loading-icon {
      animation: spin 1s linear infinite;
    }
  }
}

.message-wrapper {
  .ai-avatar {
    background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
    border: 2px solid rgba(255, 255, 255, 0.9);
    overflow: hidden;

    img {
      width: 100%;
      height: 100%;
      object-fit: cover;
    }
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 添加背景动画
@keyframes backgroundShift {
  0%, 100% {
    opacity: 1;
    transform: translateX(0) translateY(0);
  }
  50% {
    opacity: 0.8;
    transform: translateX(10px) translateY(10px);
  }
}

.waiting-message {
  margin-left: 44px; // 为了对齐其他AI消息
}

.typing-bubble {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 32px;
  min-width: 60px;
  max-width: 60px;
  padding: 0 10px;

  .typing-indicator {
    display: flex;
    align-items: center;

    span {
      height: 8px;
      width: 8px;
      margin: 0 2px;
      background-color: rgba(99, 102, 241, 0.6);
      border-radius: 50%;
      display: inline-block;
      animation: typing 1.4s infinite ease-in-out both;

      &:nth-child(1) {
        animation-delay: 0s;
      }

      &:nth-child(2) {
        animation-delay: 0.2s;
      }

      &:nth-child(3) {
        animation-delay: 0.4s;
      }
    }
  }
}

.message-info {
  font-size: 0.75rem;
  color: #6366F1;
  margin-top: 4px;
  opacity: 0.8;
}

@keyframes typing {
  0%, 80%, 100% {
    transform: scale(0.8);
    opacity: 0.6;
  }
  40% {
    transform: scale(1.2);
    opacity: 1;
  }
}

// 新增加载状态提示样式
.loading-indicator-container {
  display: flex;
  justify-content: center;
  padding: 16px 0;
  margin-bottom: 16px;
}

.loading-indicator {
  background-color: rgba(255, 255, 255, 0.9);
  border-radius: 16px;
  padding: 12px 24px;
  display: flex;
  flex-direction: column;
  align-items: center;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.1);
  border: 1px solid rgba(99, 102, 241, 0.1);
}

.loading-dots {
  display: flex;
  justify-content: center;
  margin-bottom: 8px;

  span {
    width: 8px;
    height: 8px;
    margin: 0 3px;
    background-color: #6366F1;
    border-radius: 50%;
    display: inline-block;
    animation: bounce 1.4s infinite ease-in-out both;

    &:nth-child(1) {
      animation-delay: 0s;
    }

    &:nth-child(2) {
      animation-delay: 0.2s;
    }

    &:nth-child(3) {
      animation-delay: 0.4s;
    }
  }
}

.loading-text {
  font-size: 14px;
  color: #6366F1;
  font-weight: 500;
}

@keyframes bounce {
  0%, 80%, 100% {
    transform: scale(0.6);
    opacity: 0.6;
  }
  40% {
    transform: scale(1.0);
    opacity: 1;
  }
}

/* 刷新浮窗样式 */
.refresh-widget-trigger {
  position: fixed;
  right: 20px;
  bottom: 120px;
  width: 48px;
  height: 48px;
  border-radius: 50%;
  background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  cursor: pointer;
  box-shadow: 0 4px 12px rgba(99, 102, 241, 0.3);
  z-index: 10;
  transition: transform 0.3s ease, box-shadow 0.3s ease;

  &:hover {
    transform: translateY(-3px);
    box-shadow: 0 6px 16px rgba(99, 102, 241, 0.4);
  }

  .el-icon {
    font-size: 20px;
  }
}

.refresh-widget {
  position: fixed;
  right: 20px;
  bottom: 180px;
  width: 280px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.15);
  z-index: 100;
  overflow: hidden;

  .refresh-widget-header {
    padding: 16px;
    background: linear-gradient(135deg, #6366F1 0%, #8B5CF6 100%);
    color: white;
    display: flex;
    justify-content: space-between;
    align-items: center;

    h3 {
      margin: 0;
      font-size: 16px;
      font-weight: 600;
    }

    .close-btn {
      background: none;
      border: none;
      color: white;
      font-size: 20px;
      cursor: pointer;
      padding: 0;
      margin: 0;
      line-height: 1;
    }
  }

  .refresh-widget-content {
    padding: 16px;

    p {
      margin-bottom: 16px;
      font-size: 14px;
      color: #4B5563;
    }

    .el-button {
      width: 100%;
    }
  }
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s, transform 0.3s;
}

.fade-enter-from,
.fade-leave-to {
  opacity: 0;
  transform: translateY(20px);
}
</style>